<?php

class AgencyModel extends RelationModel {

    protected $tableName = 'agency'; 
    //自动完成
    protected $_auto = array(
        array('add_time','time',3,'function'), //新增数据是插入注册时间
    );
    //自动验证email, mobile_phone, user_name
    protected $_validate = array(
        array('title','require','标题必须！'),
        array('sort','number','排序必须是数字！'),
        array('content','require','内容不能为空！'),
		array('phone', '', '手机已经存在！', 2, 'unique', 3),
        array('realname', '', '代理人已经存在！', 0, 'unique', 1),
       
    );
    protected $_link = array(
        //用户分类名称
        'userGroup' => array(
            'mapping_type' => BELONGS_TO,
            'class_name' => 'articleCategory',
            'foreign_key' => 'category_id',
            'mapping_name' => 'groupinfo',
            'as_fields' => 'name:category_name',
        ),
    );
	/**
	 * 登录指定用户
	 * @param  integer $uid 用户ID
	 * @return boolean	  ture-登录成功，false-登录失败
	 */
	public function login($username, $password) {
		if (empty($username)) {
			$this->error = '用户名不存在';
		}
		if (empty($password)) {
			$this->error = '密码不能为空';
		}
		$sqlmap = array();
		$sqlmap['realname'] = $username;
		//$sqlmap['password'] = md5($password);
		/* 检测是否在当前应用注册 */
		$user = $this->where($sqlmap)->find($uid);
		if($user['password'] != md5($password)){
			$this->error = '密码错误！'; //应用级别禁用*/
			return false;
		}
		session('DAILI_ID', $user['id']);
		session('DAILI_UNAME', $user['realname']);
		return true;
	}

	/**
	 * 注销当前用户
	 * @return void
	 */
	public function logout() {
		session(null);
	}
	/**
     * 获取列表数据
     * @param type $map
     * @return type array
     */
    public function getList($map) {
		
        $count = $this->where($map)->count();
        libfile('Page');
		$pagesize = $_GET['pagesize'];
		$pagesize = $pagesize ? $pagesize : getconfig('page_num');
        $Page = new Page($count, $pagesize);
        $Page->listRows = $pagesize;
        $result = $this->relation(true)->where($map)->order('id DESC')->limit($Page->firstRow, $Page->listRows)->select();
        $list['list'] = $result;
        $show = $Page->show();
        $list['page'] = $show;
        return $list;
    }
}
